import { useState, useEffect, Fragment } from 'react'
import { useNavigate } from 'react-router-dom'
// import { useRecoilState } from 'recoil';
// import { userState } from '../../store'
import { FormOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx'
import {
  Card,
  Button,
  Table,
  message
} from 'antd'
import { roleApi } from '../../api'
import moment from 'moment'

interface IProps {
  children?: any;
}

interface IRole {
  id: string;
  title: string;
  name: string;
  permission: string;
  created: number;
}

const displayTitleMap: any = {
  id: 'ID',
  title: '角色名称',
  name: '角色标识',
  permission: '权限',
  created: '创建时间'
}

export default function Role (props: IProps) {
  // const [userInfo, setUserInfo] = useRecoilState(userState.userInfoAtom);
  const [data, setData] = useState({list: [], total: 0})
  const [columns, setColumns] = useState([])
  const [pageTitle, setPageTitle] = useState('角色列表')

  const navigate = useNavigate()

  // 获取列表
  const getList = () => {
    roleApi.getList().then((res: any) => {
      setData(res.data)
      setPageTitle('角色列表（'+ res.data.list.length +'）')

      const columnKeys = Object.keys(res.data.list[0])
      const columns = handleColumns(columnKeys)
      setColumns(columns)
    }) 
  }

  useEffect(() => {
    getList()
  }, [])

  // 处理要展示的列
  const handleColumns = (columnKeys: any) => {
    const columns = columnKeys.map((item: string) => {
      if (item === 'created') {
        return {
          title: displayTitleMap[item],
          key: item,
          render: (record: IRole) => {
            const { created } = record
            return moment(created).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }

      return {
        title: displayTitleMap[item],
        key: item,
        dataIndex: item,
      }
    })

    columns.push({
      title: '操作',
      // dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      render: (record: IRole) => {
        // console.log({text, record, index})
        return (
          <Button.Group>
            <Button size="small" type="primary" onClick={() => toEdit(record)}>编辑</Button>
          </Button.Group>
        )
      }
    })

    return columns
  }

  const toAdd = () => {
    message.warn('新增功能暂未开放')
    // navigate('/admin/project/add')
    // navigate('add')
  }

  // 跳转到编辑页面
  const toEdit = (record: IRole) => {
    message.warn('编辑功能暂未开放')
  }

  // 导出 Excel
  const exportExcel = () => {
    // console.log('exportExcel')
    // 组装数据
    const exportData = [Object.keys(data.list[0])]
    for (let i = 0; i < data.list.length; i++) {
      // exportData.push(Object.values(data.list[i]))

      // 对字段进行个性化处理，例如：创建时间
      exportData.push([
        data.list[i]['id'],
        data.list[i]['title'],
        data.list[i]['name'],
        data.list[i]['permission'],
        moment(data.list[i]['created']).format('YYYY-MM-DD HH:mm:ss'),
      ])
    }

    // 转成 workbook
		const ws = XLSX.utils.aoa_to_sheet(exportData);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS");

		// 生成 excel 文件
		XLSX.writeFile(wb, `role-${moment().format('YYYY-MM-DD-HH-mm-ss')}.xlsx`)
  }

  return (
    <Fragment>
      <Card
        title={ pageTitle }
        bordered={false}
        extra={
          <div>
            <Button type="primary" ghost onClick={ toAdd }><FormOutlined />新增</Button>
            <Button onClick={ exportExcel }>导出Excel</Button>
          </div>
        } 
      >
        <Table
          tableLayout='auto' 
          rowKey={(record: IRole) => record.id} 
          dataSource={ data.list } 
          columns={ columns } 
          pagination={ false }
        />
      </Card>
    </Fragment>
  )
}
